package com.zhaojonhy.zhaopangwb.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.zhaojonhy.zhaopangwb.R;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.io.IOException;
import java.net.URL;


/**
 * Created by Administrator on 2016/10/8.
 */

public class WebViewActivity extends Activity {

    private ProgressBar bar;
    private WebView webView;
    private WebSettings wSettings;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String videoUrl = msg.getData().getString("videoUrl") ;
                    Log.d("WBActivity:", "msg-->"+videoUrl);
                    webView.loadUrl(videoUrl);
                    break;
            }
        }
    } ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_view);

        Intent intent = getIntent();

        final String url = intent.getStringExtra("vedioStr");

        bar = (ProgressBar) findViewById(R.id.myProgressBar);
        webView = (WebView) findViewById(R.id.webView);



        //获取WebSettings对象
        wSettings = webView.getSettings();
        //启用支持视窗meta标记（可实现双击缩放）
        wSettings.setUseWideViewPort(true);
        //以缩略图模式加载页面
        wSettings.setLoadWithOverviewMode(true);
        //设置js可以直接打开窗口，如window.open()，默认为false
        wSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //启用JavaScript支持
        wSettings.setJavaScriptEnabled(true);

        new Thread(){
            @Override
            public void run() {
                Bundle data = new Bundle() ;
                Message msg = new Message() ;
                data.putString("videoUrl",useHtmlParser(url) );
                msg.setData(data);
                handler.sendMessage(msg) ;
            }
        }.start();

        //设置将接收各种通知和请求的WebViewClient（在WebView加载所有的链接）
        webView.setWebChromeClient(new myWebChromeClient());

        // 如果页面中链接，如果希望点击链接继续在当前browser中响应，
        // 而不是新开Android的系统browser中响应该链接，必须覆盖webview的WebViewClient对象
        webView.setWebViewClient(new myWebViewClient());
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    //go back
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        Log.d("WBActivity:", "keyCode-->" + keyCode);
        Log.d("WBActivity:", "KeyEvent.KEYCODE_BACK-->" + KeyEvent.KEYCODE_BACK);

        // Check if the key event was the Back button and if there's history
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: //处理返回事件
                Log.d("WBActivity:", "webView.canGoBack()-->" + webView.canGoBack());
                if (webView.canGoBack()) {
                    webView.goBack();//让WebView回退到上一个网页
                    return true;
                } else {//如果WebView不能回退
                    WebViewActivity.this.finish();//退出程序
                }
                break;
            case KeyEvent.KEYCODE_SEARCH://当
//          webView.loadUrl("");
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    /**
     * webView视图客户端
     *
     * @author Administrator
     */
    class myWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
//          return super.shouldOverrideUrlLoading(view, url);
//            Log.d("WBActivity:","url-->" + url) ;
//            webView.loadUrl(url);
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Log.d("wbActivity", "Error-->" + error);
            super.onReceivedError(view, request, error);
        }

    }

    class myWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                bar.setVisibility(View.INVISIBLE);
            } else {
                if (View.INVISIBLE == bar.getVisibility()) {
                    bar.setVisibility(View.VISIBLE);
                }
                bar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        webView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        webView.onPause();
        super.onPause();
    }

    private String useHtmlParser(String url) {
        String resultUrl = "" ;
        Log.d("WBActivity:", "useHtmlParser()-->" + "OK");
        try {
            Parser parser = new Parser((new URL(url)).openConnection());
// 创建 html parser 对象，并指定要访问网页的 URL 和编码格式
            parser.setEncoding("UTF-8");
            String postTitle = "";
// 获取指定的 div 节点，即 <div> 标签，并且该标签包含有属性 id 值为“tab1”
            NodeFilter videoNodeFilter = new NodeFilter() {
                @Override
                public boolean accept(Node node) {
                    if(node.getText().startsWith("video")){
                        return true;
                    }else {
                        return false;
                    }
                }
            };
            NodeFilter embedNodeFilter = new NodeFilter() {
                @Override
                public boolean accept(Node node) {
                    if(node.getText().startsWith("embed")){
                        return true;
                    }else {
                        return false;
                    }
                }
            };
//            //OrFilter 来设置过滤 <a> 标签，<img> 标签和 <frame> 标签，三个标签是 or 的关系
//            OrFilter orFilter = new OrFilter(new NodeClassFilter(LinkTag.class), new
//                    NodeClassFilter(ImageTag.class));
//            OrFilter linkFilter = new OrFilter(orFilter, videoNodeFilter);
            OrFilter linkFilter = new OrFilter(embedNodeFilter, videoNodeFilter);

            //得到所有经过过滤的标签
            // 得到所有经过过滤的标签，结果为NodeList
            NodeList list = parser.extractAllNodesThatMatch(linkFilter);
            for (int i = 0; i < list.size(); i++) {
                Node tag = list.elementAt(i);
                if(tag instanceof LinkTag){ //<a>标签
                    LinkTag link = (LinkTag) tag;
                    String linkUrl = link.getLink();//url
                    String text = link.getLinkText();//链接文字
                    Log.d("WBActivity:","linkUrl-->"+linkUrl + "**********" + text);
                }else if(tag instanceof ImageTag){//<img>标签
                    ImageTag image = (ImageTag) list.elementAt(i);
                    Log.d("WBActivity:","imageUrl-->"+image.getImageURL() + "********");//图片地址
                    Log.d("WBActivity:","imageText-->"+image.getText());//图片文字
                }else{//<video> 标签
                    //提取 video 里 src 属性的链接如 <video src="test.html"/>
                    String video = tag.getText();
                    int start = video.indexOf("src");
                        video = video.substring(start);
                    int end = video.indexOf(" ");
                    if (end == -1) {
                        end = video.indexOf(">");
                    }
                    video = video.substring(5, end - 1);
                    resultUrl = video ;
                    Log.d("WBActivity:","videoUrl-->"+video);//视频地址

//                    int start ;
//                    int end ;
//                    if(video.startsWith("video")){
//                        start = video.indexOf("src");
//                        video = video.substring(start);
//                        end = video.indexOf(" ");
//                        if (end == -1) {
//                            end = video.indexOf(">");
//                    }else if(video.startsWith("embed")){
//                        start = video.indexOf("***");
//                        video = video.substring(start);
//                        end = video.indexOf(" ");
//                        if (end == -1) {
//                            end = video.indexOf(">");
//                        }
                }

            }
        }catch (ParserException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return resultUrl ;
    }


}
